<template>
  <base-window :unique="unique" :title="title" size="small" :show.sync="visible" width="432px" @closed="closed" class="task-need-approve-dialog">
    <div class="base-modal-content">
      <p><span class="form-item-required" v-if="remarkRequired">*</span>{{$t('task.detail.components.approveDesc')}}：</p>
      <biz-at-textarea class="biz-at-textarea" ref="atTextarea" search-url="/message/user/lists" name-key="displayName" v-model="apprForm.applyRemark" :at-users.sync="atUsers" direction="bottom">
        <template slot="item" slot-scope="item">
          <img :src="head(item.user.head)">
          <span>{{item.user.displayName}}</span>
        </template>
        <textarea ref="editor" class="base-at-textarea" @input="inputContent" :placeholder="remarkPlaceholder" maxlength="500" :rows="3"></textarea>
      </biz-at-textarea>
      <div class="vip-info">{{$t('common.zhongqi.vipApproveTipText')}}:</div>
      <div class="approve-steps">
        <el-steps direction="vertical">
          <el-step v-for="(item, index) in vipList" :key="index" :title="setNameLanguage(item.data)" status="process">
            <el-row slot="description" type="flex">
              <div class="form-item-control">
                <label>{{$t('common.base.approveUser')}}：</label>
                <template v-if="(item.data && item.data.attribute && item.data.attribute.candidate)">
                  <span>
                    {{ item.data.attribute.candidate | vipApproveNames }}
                  </span>
                </template>
                <template v-else>
                  {{$t('task.tip.approveTip8', {name: $t('task.edit.approvers')})}}
                </template>
              </div>
            </el-row>
          </el-step>
        </el-steps>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button :disabled="pending" @click="closed">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="submit" :loading="pending">{{$t('common.base.submit')}}</el-button>
    </div>
  </base-window>
</template>

<script>
/* util*/
import { t } from '@src/locales'
import { getOssUrl } from '@src/util/assets'
import { getSortAfterNodes } from "@src/util/approve";
import {enCodeAtText, getReceivers} from "@src/util/atText";
import {useRootUser, useTenantId} from "@hooks/useRootWindow";
import {cutAtTextContent} from "pub-bbx-utils";
const defaultAvatar = getOssUrl('/avatar.png')
/* api*/
import {createEventApproval} from "@src/api/EventApi";

export default {
  name: "AdvancedApprovalDialog",
  props: {
    unique: {
      type: Boolean,
      default: true
    },
    title: {
      type: String,
      default: t('task.tip.proposeApproveTip1'),
    },
    remarkRequired: {
      type: Boolean,
      default: false
    },
    objId: {
      type: String,
      default: '',
    },
    objNo: {
      type: String,
      default: '',
    },
    module: {
      type: String,
      default: 'event',
    }
  },
  computed: {
    remarkPlaceholder() {
      return this.remarkRequired ? t('task.tip.proposeApproveTip2') : t('task.tip.proposeApproveTip3')
    },
    // 高级审批接口
    approvalMethods() {
      return {
        'event': createEventApproval
      }?.[this.module]
    },
  },
  data() {
    return {
      visible: false,
      apprForm: {},
      atUsers:[],
      pending: false,
      vipList: [],
      allParams: {},
    }
  },
  filters: {
    vipApproveNames(approvers) {
      return approvers.map(item => item.name).join(',')
    },
  },
  methods: {
    setNameLanguage(data) {
      if (!data.attribute.nameLanguage) return data.name
      let laEnv = this.$i18n.locale ;
      return data.attribute.nameLanguage[laEnv]
    },
    head(src){
      if(!src) return defaultAvatar;
      return src;
    },
    inputContent(event){
      let value = event.target.value;
      this.apprForm.applyRemark = value;
    },

    async openDialog(data) {
      try {
        this.allParams = data;

        let vipJson = JSON.parse(data.attribute)
        if (vipJson?.cells) {
          // 开始解析数据
          let filterArr = await getSortAfterNodes(vipJson.cells)
          let approveArr = filterArr?.filter((item => item?.shape === 'approve-node'))
          this.vipList = approveArr
        }

        this.visible = true;
      } catch (e) {
        console.error(e)
      }
    },

    closed() {
      this.visible = false;
      this.$emit('closed')
    },

    async submit() {
      try {
        if(this.pending) return;

        this.pending = true;

        // 审批说明必填校验
        if (!this.apprForm.applyRemark && this.remarkRequired) return this.$platform.notification({ type: 'error', title: this.$t('task.tip.proposeApproveTip4')})

        let approveVipParams = {
          objId: this.objId,
          action: this.allParams?.action ?? '',
          applyRemark: enCodeAtText(this.apprForm.applyRemark, this.atUsers),
          params: {
            ...this.allParams?.params ?? {}
          }
        }

        let receivers = ''
        let query = ''
        if(this.apprForm.applyRemark){
          receivers = getReceivers(this.apprForm.applyRemark, this.atUsers)
          const queryData = {
            receivers,
            tenantId: useTenantId().value,
            content: cutAtTextContent(this.apprForm.applyRemark),
            sendUserName: useRootUser().value?.displayName,
            bizId: this.objId,
            bizNo: this.objNo || this.$t('event.detail.components.dialog.text36'),
            md: 'event'
          };
          query = '?';
          for (let i in queryData) {
            query += `&${i}=${queryData[i]}`;
          }
        }

        // 高级审批接口
        const { success, message } = await this.approvalMethods(query, approveVipParams);

        if(!success) return this.$message.error(message);

        this.$emit('success')
      } catch (e) {
        console.error(e)
      } finally {
        this.pending = false;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.vip-info {
  margin: 20px 0 10px 0;
}
</style>